package org.example.common.interceptor;

import cn.hutool.core.util.RandomUtil;
import org.example.common.constant.Constants;
import org.slf4j.MDC;

/**
 * 请求 ID 上下文
 *
 * @author dingcan
 */
public class TraceIdContext {
    
    private TraceIdContext() {
    }
    
    public static String createTraceId() {
        return RandomUtil.randomString(16);
    }
    
    public static void setTraceId(String traceId) {
        if (traceId != null && !traceId.isEmpty()) {
            MDC.put(Constants.TRACE_ID, traceId);
        }
    }
    
    public static String getTraceIdFromMDC() {
        String traceId = MDC.get(Constants.TRACE_ID);
        if (traceId == null) {
            return "";
        }
        return traceId;
    }
    
    public static void removeTraceId() {
        MDC.remove(Constants.TRACE_ID);
    }
}